package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.Interface.UserRepo;
import com.example.demo.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Controller
public class GetUser {

    @Resource
    UserRepo userRepo;

    /*
     * 查询所有用户
     * */
    @RequestMapping(value = "/getuser")
    @ResponseBody
    public String getuser() {
        List<User> userList = new ArrayList<>();
        List<User> optionalData = userRepo.findAll();//查询所有数据
        for (User user : optionalData) {
            int id = user.id;
            String name = new String(user.name);
            String password = new String(user.password);
            User user1 = new User();
            user1.id = id;
            user1.name = name;
            user1.password = password;

            userList.add(user1);

            // String s = JSON.toJSONString(userList);


        }
        JSONObject obj = new JSONObject();
        //前台通过key值获得对应的value值
        obj.put("code", 0);
        obj.put("msg", "");
        obj.put("count", 1000);
        obj.put("data", userList);
        return obj.toJSONString();
    }


    /*
     *
     * 通过ID删除相应的用户
     * */
    @RequestMapping(value = "/deleteuser")
    @ResponseBody
    public String delete(HttpServletRequest req, HttpServletResponse rsp) {
        String id = req.getParameter("id");
        System.out.print(id);
        userRepo.deleteById(Integer.parseInt(id));
        /*
        JSONObject obj = new JSONObject();
        //前台通过key值获得对应的value值
        obj.put("code", 200);
        obj.put("msg", "删除成功");
        obj.put("count", 1000);
        obj.put("data", "");
        return obj.toJSONString();
         */
        return "success";

    }

    /*
    * 通过传输的ID值更新用户信息
    *
    * */

    @RequestMapping(value = "/update")
    @ResponseBody
    public String update(HttpServletRequest req, HttpServletResponse rsp){
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        System.out.print(id);
        System.out.print(name);
        System.out.print(password);

        //更新数据
        User user = userRepo.findById(Integer.parseInt(id)).get();//获取指定ID的对象
        user.setName(name);
        user.setPassword(password);
        userRepo.save(user);

        return "success";
    }


}
